package org.lee.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.lee.mq.config.RabbitMqConstants;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Random;


/**
 * @author jackielee
 * @version 1.0
 * @description NotifyMessageReceiver
 * @date 2021/7/5
 **/
//@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "receiver-pay", havingValue = "true")
@Component
@Slf4j
public class NotifyPayMessageReceiver {

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "#{queueNames." + RabbitMqConstants.QUEUE_NAME_SHORT_PAY + "}", durable = "true"),
            exchange = @Exchange(name = RabbitMqConstants.ORDER_PAY_NOTIFY_EXCHANGE_NAME, durable = "true", type = "topic", ignoreDeclarationExceptions = "true"),
            key = RabbitMqConstants.ORDER_ROUTE_KEY_ALL))
    @RabbitHandler
    public void onPayMessage(Message message, Channel channel) throws IOException {

        log.info("消息：{}", message);
        MessageHeaders headers = message.getHeaders();
        String routeKey = headers.get(AmqpHeaders.RECEIVED_ROUTING_KEY).toString();
        // spring.rabbitmq.listener.simple.acknowledge-mode=manual
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

        log.warn("{} the message has not any manager of it.", routeKey);
        boolean ok = new Random().nextBoolean();
        if (ok) {
            channel.basicAck(deliveryTag, false);
        } else {
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
